package com.nice.client;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;

import java.util.Scanner;

import com.nice.message.Message;
import com.nice.message.MessageCodec;

public class Client {
	public static void main(String[] args) {
		EventLoopGroup group = new NioEventLoopGroup();
		Bootstrap bt = new Bootstrap();
		bt.group(group);
		bt.channel(NioSocketChannel.class);
		bt.option(ChannelOption.TCP_NODELAY, true);
		bt.handler(new ChannelInitializer<SocketChannel>() {

			@Override
			protected void initChannel(SocketChannel arg0) throws Exception {
				ChannelPipeline pipe = arg0.pipeline();
				pipe.addLast(new MessageCodec());
				pipe.addLast(new SimpleChannelInboundHandler<Message>() {

					@Override
					public void channelActive(ChannelHandlerContext ctx)
							throws Exception {
						Message login = new Message();
						login.type = Message.LOGIN;
						login.from = 1002;
						ctx.writeAndFlush(login);
						System.out.println("send login message");
					}

					@Override
					protected void messageReceived(ChannelHandlerContext arg0,
							Message arg1) throws Exception {
						System.out.println(arg1);
					}
				});
				pipe.addLast(new MessageCodec());
			}
		});
		System.out.println("connect ser ok enter message");
		Channel ch = bt.connect("127.0.0.1", 2001).channel();
		Scanner sc = new Scanner(System.in);
		String line = "";
		byte[] data = ImagUtil.readImg("./img/test.png");
		while (!line.equals("q")) {
			line = sc.nextLine();
			Message msg = new Message();
			msg.from = 1002;
			msg.to = 1001;
			msg.type=1;
			msg.len = data.length;
			msg.body = data;
			ch.writeAndFlush(msg);
		}
		sc.close();
		group.shutdownGracefully();
	}
}
